package cn.jasonone.hm.netdisc.controller;

import cn.jasonone.hm.netdisc.consts.SystemConst;
import cn.jasonone.hm.netdisc.model.dto.HttpResult;
import cn.jasonone.hm.netdisc.model.pojo.DiskInfo;
import cn.jasonone.hm.netdisc.model.pojo.FileType;
import cn.jasonone.hm.netdisc.model.pojo.UserInfo;
import cn.jasonone.hm.netdisc.service.DiskInfoService;
import cn.jasonone.hm.netdisc.service.FileTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author Jason
 * @date 2020-07-23 16:20:07
 */
@Controller
@RequestMapping("/diskInfo")
@Slf4j
public class DiskInfoController {
	@Resource
	private DiskInfoService diskInfoService;
	@Resource
	private FileTypeService fileTypeService;
	@Value("${fileupload.root-path}")
	private String rootPath;
	
	@GetMapping(produces = MediaType.TEXT_HTML_VALUE)
	public String home(){return "diskInfo/index";}
	
	@GetMapping
	@ResponseBody
	public HttpResult findAll(DiskInfo diskInfo,@SessionAttribute(SystemConst.SESSION_LOGIN_STATUS) UserInfo userInfo){
		if(diskInfo==null || diskInfo.getPid() == null){
			if(diskInfo == null){
				diskInfo=new DiskInfo();
			}
			diskInfo.setPid(-1);
		}
		if(diskInfo.getUserId() == null){
			diskInfo.setUserId(userInfo.getId());
		}
		List<DiskInfo> list = diskInfoService.findAll(diskInfo);
		return HttpResult.success("查询成功").setData(list);
	}
	@PostMapping("/createDir")
	@ResponseBody
	public HttpResult createDirectory(DiskInfo diskInfo,@SessionAttribute(SystemConst.SESSION_LOGIN_STATUS) UserInfo userInfo){
		DiskInfo disk=new DiskInfo();
		disk.setPid(diskInfo.getPid());
		disk.setUserId(userInfo.getId());
		disk.setDirectory(true);
		disk.setName(diskInfo.getName());
		disk.setPid(diskInfo.getPid());
		DiskInfo directory = this.diskInfoService.getDirectory(disk.getName(), disk.getPid(), userInfo.getId());
		if(directory != null){
			disk.setId(directory.getId());
		}
		diskInfoService.save(disk);
		return HttpResult.success("文件夹创建成功");
	}
	
	@PostMapping("/fileUpload")
	@ResponseBody
	public HttpResult fileUpload(DiskInfo diskInfo, @RequestParam("file")MultipartFile file,@SessionAttribute(SystemConst.SESSION_LOGIN_STATUS) UserInfo userInfo){
		try {
			Path root = Paths.get(rootPath);
			if(!Files.exists(root)){
				Files.createDirectories(root);
			}
			DiskInfo disk=new DiskInfo();
			disk.setPid(diskInfo.getPid());
			disk.setUserId(userInfo.getId());
			disk.setDirectory(false);
			//计算MD5
			String path = DigestUtils.md5DigestAsHex(file.getInputStream());
			Path resolve = root.resolve(path);
			if(Files.exists(resolve)){
			
			}else{
				//转储文件
				file.transferTo(resolve);
			}
			try(InputStream is = Files.newInputStream(resolve)){
				byte[] buff=new byte[64];
				for (int i = 0; i < buff.length; i++) {
					buff[i]= (byte) is.read();
				}
				FileType fileType = fileTypeService.parseFileType(buff);
				if(fileType == null){
					throw new IOException("不支持的文件类型:"+file.getOriginalFilename());
				}
				disk.setType(fileType.getId());
			}
			disk.setPath(path);
			disk.setName(file.getOriginalFilename());
			disk.setSize(file.getSize());
			diskInfoService.save(disk);
			return HttpResult.success("文件上传成功");
		} catch (IOException e) {
			log.error("文件上传失败", e);
			return HttpResult.create(500, e.toString());
		}
	}
	@RequestMapping("/deleteFiles")
	@ResponseBody
	public HttpResult deleteFiles(@RequestParam("ids[]") Integer[] ids ){
		if(ids==null || ids.length==0){
			log.error("文件删除失败", ids);
			return HttpResult.create(500,"参数传入失败");
		}
		diskInfoService.deleteByIds(true, ids);
		return HttpResult.success("删除成功");
	}
}
